﻿namespace DHTools
{
    public class FileProcessor
    {
        private int _totalFiles;
        private int _processedFiles;
        private readonly object _progressLock = new object();
        private readonly int _maxThreadCount;

        public delegate void ProgressFinishEventHandler();
        public event ProgressFinishEventHandler OnAllFilesProcessed;

        public delegate void ProgressChangedEventHandler(double progress);
        public event ProgressChangedEventHandler OnProgressChanged;

        public FileProcessor(int maxThreadCount)
        {
            _maxThreadCount = maxThreadCount;
        }

        /// <summary>
        /// Processes a list of files in parallel.
        /// </summary>
        public void ProcessFiles(List<string> files, Action<string> processFileAction)
        {
            _totalFiles = files.Count;
            _processedFiles = 0;

            var options = new ParallelOptions
            {
                MaxDegreeOfParallelism = _maxThreadCount
            };

            Parallel.ForEach(files, options, file =>
            {
                processFileAction(file);
                UpdateProgress();
            });

            OnAllFilesProcessed?.Invoke();
        }

        private void UpdateProgress()
        {
            lock (_progressLock)
            {
                _processedFiles++;
                double progress = (double)_processedFiles / _totalFiles * 100;
                OnProgressChanged?.Invoke(progress);
            }
        }
    }
}